#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'set'
require_relative '../defconfig.rb'

ca_path = '/etc/compass-ci/ca'
crt_path = "#{ca_path}/server.crt"
key_path = "#{ca_path}/server.key"

unless File.exist?(crt_path) && File.exist?(key_path)
  puts 'CA certificate is missing. Ignore if the HTTPS scheduler is not required'
  exit
end

names = Set.new %w[
  SCHED_HOST
  SCHED_PORT
  SCHED_HTTPS_HOST
  SCHED_HTTPS_PORT
  REDIS_HOST
  REDIS_PORT
  ES_HOST
  ES_PORT
  ES_USER
  ES_PASSWORD
  OS_HTTP_HOST
  OS_HTTP_PORT
  INITRD_HTTP_HOST
  INITRD_HTTP_PORT
  TASKQUEUE_PORT
  TASKQUEUE_HOST
  GIT_SERVER
  MASTER_FLUENTD_HOST
  MASTER_FLUENTD_PORT
  SSHR_PORT
  SSHR_PORT_BASE
  SSHR_PORT_LEN
  lab
]

defaults = relevant_defaults(names)
defaults['SSHR_PORT'] ||= 5051
defaults['SSHR_PORT_BASE'] ||= 21000
defaults['SSHR_PORT_LEN'] ||= 2000
defaults['SCHED_PORT'] ||= '3000'
defaults['SCHED_HOST'] ||= '172.17.0.1'
defaults['MASTER_FLUENTD_PORT'] ||= '24224'
defaults['SCHED_HTTPS_PORT'] ||= 20002
defaults['SCHED_HTTPS_HOST'] ||= 'api.compass-ci.openeuler.org'
env = docker_env(defaults)

CCI_REPOS = ENV['CCI_REPOS'] || '/c'
DEFAULT_LKP = "#{CCI_REPOS}/lkp-tests"
DEFAULT_CCI = "#{CCI_REPOS}/compass-ci"
LAB = defaults['lab'] || 'z9'
SCHED_HTTPS_PORT = defaults['SCHED_HTTPS_PORT']
SCHED_HTTPS_HOST = defaults['SCHED_HTTPS_HOST']

docker_rm "s001-alpine-#{SCHED_HTTPS_PORT}"

cmd = %W[
  docker run
  --restart=always
  --name s001-alpine-#{SCHED_HTTPS_PORT}
  -d
  -u 1090:1090
  -p #{SCHED_HTTPS_PORT}:#{defaults['SCHED_HTTPS_PORT']}
] + env + %W[
  -e LKP_SRC=#{DEFAULT_LKP}
  -e CCI_SRC=#{DEFAULT_CCI}
  -e NODE_PORT=#{SCHED_HTTPS_PORT}
  -v #{ENV['LKP_SRC']}:#{DEFAULT_LKP}
  -v #{ENV['CCI_SRC']}:#{DEFAULT_CCI}
  -v #{CCI_REPOS}/lab-#{LAB}:#{CCI_REPOS}/lab-#{LAB}
  -v /srv/cci/scheduler/alpine:/srv/cci/scheduler
  -v /etc/localtime:/etc/localtime:ro
  -v /srv/result:/srv/result
  -v /srv/initrd:/srv/initrd:ro
  -v /srv/os:/srv/os:ro
  -v /etc/compass-ci:/etc/compass-ci:ro
  -v /srv/upload-files:/srv/upload-files:rw
  --log-opt mode=non-blocking
  --log-opt max-buffer-size=4m
  --log-opt tag=scheduler-#{SCHED_HTTPS_PORT}
  sch-ruby-a:v0.00d-#{defaults['SCHED_PORT']}
]

cmd += ['sh', '-c', "umask 002 && ./scheduler --ssl --ssl-key-file #{ca_path}/server.key --ssl-cert-file #{ca_path}/server.crt"]

system(*cmd)
